import { Table, Pagination, Tooltip } from 'antd'
import type { PaginationProps } from 'antd'
import { RedoOutlined } from '@ant-design/icons'

import './index.scss'
import { useEffect, useState } from 'react'

type ColItems = {
  title: string
  dataIndex: string
  width?: number
  align?: 'center' | 'left' | 'right'
  ellipsis?: { showTitle: boolean }
  render?: (key: string) => JSX.Element
}

interface TableProps<T> {
  total: number
  tableHeaders: ColItems[]
  getTableData: (pageIndex: number, pageSize: number) => Promise<T[]>
}

const defaultCol: ColItems = {
  title: '',
  dataIndex: '',
  width: 100,
  align: 'center',
  ellipsis: {
    showTitle: false
  },
  render: (key: string) => (
    <Tooltip placement="topLeft" title={key}>
      {key}
    </Tooltip>
  )
}

function MyTable<T>(props: TableProps<T>) {
  const { tableHeaders, getTableData, total } = props

  const newTableHeaders = tableHeaders.map((item) => ({ ...defaultCol, ...item }))

  const [tableData, setTableData] = useState<T[]>([])

  const [pageSize, setPageSize] = useState(10)
  const [pageIndex, setPageIndex] = useState(1)

  const onChange: PaginationProps['onChange'] = async (pageIndex, pageSize) => {
    setPageIndex(pageIndex)
    setPageSize(pageSize)
  }

  const showTotal: PaginationProps['showTotal'] = (total) => `共 ${total} 条`

  useEffect(() => {
    const getData = async () => {
      const data = await getTableData(1, pageSize)
      setTableData(data)
    }
    getData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageSize, pageIndex])

  const refresh = () => getTableData(pageIndex, pageSize)

  return (
    <div className="custom-mtable">
      <Table
        bordered
        size="small"
        columns={newTableHeaders}
        dataSource={tableData as any}
        pagination={false}
        scroll={{ y: 'calc(100% - 40px)' }}
        className="custom-table"
      />

      <div className="custom-bottom">
        <RedoOutlined onClick={refresh} />
        <Pagination
          size="small"
          total={total}
          current={pageIndex}
          pageSize={pageSize}
          showTotal={showTotal}
          showSizeChanger
          showQuickJumper
          onChange={onChange}
        />
      </div>
    </div>
  )
}

export default MyTable
